// pages/scanForPay/voucherList/index.js
const common = require("../../../public.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    getSaveHasSelectList:[],
    acIdList:[],
    isOverShare:true,
    cityCouponList: [  // 存储企业券和非叠加券 的列表集合。   企业券，门店后台发出
      // {
      //   exceedMoney:50,
      //   discountsMoney:100,
      //   type:1,
      //   couponName:"枣庄家电惠民",
      //   couponTypeName:'扫码付款直接抵扣'
      // },
    
    ], //省券列表
    cityCouponListss: [// 存储叠加券。   发券平台发出
      // {
      //   exceedMoney:0,
      //   discountsMoney:100,
      //   type:1,
      //   couponName:"枣庄家电惠民",
      //   couponTypeName:'扫码付款直接抵扣'
      // },
     
    ], //省券列表
   
    radio: '1',
    activeSelect: -1,
    activeSelectS: -1,
    newArr: [],
    selectD: true, //默认多选为全不选
    selectSingle: true, //默认全不
    paymentValue: '',// 上个界面输入的付款金额。 paymentValue、surplusNum、ss默认值都是上个界面输入的付款金额
    surplusNum: 0,// 上个界面输入的付款金额。
    ss: 0,// 上个界面输入的付款金额。
    tempVoucherList:[
        {
          "couponNo": "5H9K70462V",
          "status": "2",
          "acId": 923,
          "type": 4,
          "userId": 29719,
          "phone": null,
          "createTime": null,
          "receiveTime": 1684118155000,
          "confirmTime": null,
          "couponTypeName": "枣庄市",
          "endTime": 1684377355000,
          "couponName": "产研优惠券详情测试",
          "discountsMoney": 0.09,
          "exceedMoney": 0.10,
          "cityName": null,
          "managerId": 191,
          "remark": "",
          "isConvertOver": null,
          "isConvert": null,
          "zgCouponNo": null,
          "tzAreaFlag": null,
          "isComposit": 1,
          "refundType": null,
          "hxCouponNo": null,
          "checkStatus": null
        },
        {
            "couponNo": "5H9K70462V",
            "status": "2",
            "acId": 923,
            "type": 5,
            "userId": 29719,
            "phone": null,
            "createTime": null,
            "receiveTime": 1684118155000,
            "confirmTime": null,
            "couponTypeName": "枣庄市",
            "endTime": 1684377355000,
            "couponName": "222产研优惠券详情测试",
            "discountsMoney": 0.09,
            "exceedMoney": 0.10,
            "cityName": null,
            "managerId": 191,
            "remark": "",
            "isConvertOver": null,
            "isConvert": null,
            "zgCouponNo": null,
            "tzAreaFlag": null,
            "isComposit": 1,
            "refundType": null,
            "hxCouponNo": null,
            "checkStatus": null
          },
          {
            "couponNo": "1H6NGH273D",
            "status": "2",
            "acId": 890,
            "type": 5,
            "userId": 29719,
            "phone": null,
            "createTime": null,
            "receiveTime": 1684128623000,
            "confirmTime": null,
            "couponTypeName": "枣庄市",
            "endTime": 1684387823000,
            "couponName": "产研消费券新版测试券B",
            "discountsMoney": 0.09,
            "exceedMoney": 0.10,
            "cityName": null,
            "managerId": 191,
            "remark": "",
            "isConvertOver": null,
            "isConvert": null,
            "zgCouponNo": null,
            "tzAreaFlag": null,
            "isComposit": 2,
            "refundType": null,
            "hxCouponNo": null,
            "checkStatus": null
          },
          {
            "couponNo": "46YJE021HK",
            "status": "2",
            "acId": 891,
            "type": 4,
            "userId": 29719,
            "phone": null,
            "createTime": null,
            "receiveTime": 1684128632000,
            "confirmTime": null,
            "couponTypeName": "枣庄市",
            "endTime": 1684387832000,
            "couponName": "产研消费券新版测试券C",
            "discountsMoney": 0.04,
            "exceedMoney": 0.10,
            "cityName": null,
            "managerId": 191,
            "remark": "",
            "isConvertOver": null,
            "isConvert": null,
            "zgCouponNo": null,
            "tzAreaFlag": null,
            "isComposit": 3,
            "refundType": null,
            "hxCouponNo": null,
            "checkStatus": null
          }
      ],


  },
  // 单选中
  checkedS(e) {

    var arr = []
    console.log(e.currentTarget.dataset.index,"e.currentTarget.dataset.indexe.currentTarget.dataset.index")
    var actIndex = e.currentTarget.dataset.index
    if (this.data.paymentValue < e.currentTarget.dataset.item.exceedMoney) {
      common.showToast('满' + e.currentTarget.dataset.item.exceedMoney + '可用')
      return
    }
    if (this.data.cityCouponList.findIndex(item => item.select == true) == -1 && this.data.surplusNum < e.currentTarget.dataset.item.discountsMoney) {
      return
    }
    var surplusNums = this.data.surplusNum
    var surplusNumss = this.data.ss
    console.log('____surplusNums___',surplusNums,'++++surplusNumss+++',surplusNumss);
    // 固定的量
    for (var i = 0; i < this.data.cityCouponList.length; i++) {
      if (i == actIndex) {   //选中true
        console.log('aaa==');
        this.data.cityCouponList[i].select = !this.data.cityCouponList[i].select
        if (this.data.cityCouponList[i].select) {  // 选中
          this.data.cityCouponList[actIndex].selectTwo = false
          var surplusNum = surplusNumss - e.currentTarget.dataset.item.discountsMoney;
          this.setData({
            selectSingle: false,
            surplusNum
          })
        } else {
          var surplusNum = this.data.surplusNum + e.currentTarget.dataset.item.discountsMoney;
          this.setData({
            selectSingle: true,
            surplusNum,
            ss: surplusNum
          })
        }
      } else {
        console.log('bbb==');
        if (this.data.cityCouponList.findIndex(target => target.select == true) == -1) {
          this.setData({
            selectSingle: true
          })
        }
        this.data.cityCouponList[i].select = false
        this.data.cityCouponList[i].selectTwo = !this.data.cityCouponList[i].selectTwo
      }
    }
    this.setData({
      activeSelect: actIndex,
      cityCouponList: this.data.cityCouponList
    })
  },
  // 多选
  checkedD(e) {
    var actIndex = e.currentTarget.dataset.index
    // 不选择状态，全部是false
    if (this.data.paymentValue < e.currentTarget.dataset.item.exceedMoney) {
      common.showToast('满' + e.currentTarget.dataset.item.exceedMoney + '可用')
      return
    }
    else if (this.data.surplusNum < e.currentTarget.dataset.item.discountsMoney) {
      if (!e.currentTarget.dataset.item.select) {
        for (var i = 0; i < this.data.cityCouponListss.length; i++) {
          if (i == actIndex) {
            this.data.cityCouponListss[actIndex].select = !this.data.cityCouponListss[actIndex].select
            if (!this.data.cityCouponListss[actIndex].select) { //选中false
              var surplusNum = this.data.surplusNum - e.currentTarget.dataset.item.discountsMoney;
              // this.data.cityCouponListss[actIndex].acId
              for (var k = 0; k < this.data.cityCouponListss.length; k++) {
                console.log(this.data.cityCouponListss[k])
                if (this.data.cityCouponListss[actIndex].acId == this.data.cityCouponListss[k].acId) {
                  if (actIndex != k) {
                    this.data.cityCouponListss[k].repeat = true
                    console.log(k)
                  }
                }
              }
              this.setData({
                surplusNum,
                ss: surplusNum
              })
            } else {
              var surplusNum = this.data.surplusNum + e.currentTarget.dataset.item.discountsMoney;
              this.data.cityCouponListss[actIndex].acId
              for (var k = 0; k < this.data.cityCouponListss.length; k++) {
                console.log(this.data.cityCouponListss[k])
                if (this.data.cityCouponListss[actIndex].acId == this.data.cityCouponListss[k].acId) {
                  if (actIndex != k) {
                    this.data.cityCouponListss[k].repeat = false
                    console.log(k)
                  }
                }
              }
              this.setData({
                surplusNum,
                ss: surplusNum
              })
            }
          }
        }
        this.setData({
          activeSelectS: actIndex,
          cityCouponListss: this.data.cityCouponListss, //点击的状态
        })
      }
      return
    }
    if (e.currentTarget.dataset.item.repeat) {   //重复
      console.log("重复666")
      return
  }
    for (var i = 0; i < this.data.cityCouponListss.length; i++) {
      if (i == actIndex) {
        this.data.cityCouponListss[actIndex].select = !this.data.cityCouponListss[actIndex].select
        if (!this.data.cityCouponListss[actIndex].select) { //选中false
          this.data.cityCouponListss[actIndex].acId
          for (var k = 0; k < this.data.cityCouponListss.length; k++) {
            console.log(this.data.cityCouponListss[k])
            if (this.data.cityCouponListss[actIndex].acId == this.data.cityCouponListss[k].acId) {
              if (actIndex != k) {
                this.data.cityCouponListss[k].repeat = true
                console.log(k)
              }
            }
          }
          var surplusNum = this.data.surplusNum - e.currentTarget.dataset.item.discountsMoney;
          this.setData({
            surplusNum,
            ss: surplusNum
          })
        } else {
          var surplusNum = this.data.surplusNum + e.currentTarget.dataset.item.discountsMoney;
          this.data.cityCouponListss[actIndex].acId
          for (var k = 0; k < this.data.cityCouponListss.length; k++) {
            console.log(this.data.cityCouponListss[k])
            if (this.data.cityCouponListss[actIndex].acId == this.data.cityCouponListss[k].acId) {
              if (actIndex != k) {
                this.data.cityCouponListss[k].repeat = false
                console.log(k)
              }
            }
          }
          this.setData({
            surplusNum
          })
        }
      }
    }
    this.setData({
      activeSelectS: actIndex,
      cityCouponListss: this.data.cityCouponListss, //点击的状态
    })
  },
  onChange(event) {
    console.log(event, "ceshiceshi")
    this.setData({
      radio: event.detail,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.storeId = options.storeId
    this.data.userId = options.userId
    this.data.token = options.token

    this.setData({
      paymentValue: parseFloat(options.paymentValue),
      surplusNum: parseFloat(options.paymentValue),
      ss: parseFloat(options.paymentValue),
      getSaveHasSelectList:options.saveHasSelectList?JSON.parse(options.saveHasSelectList):[],
    },()=>{
        console.log('传递的---',this.data.getSaveHasSelectList);
    })
    // this.getDiscountCoupon()
    this.copuStoreList()
  },
  copuStoreList() {
    var that = this
    var tempJson = {
        storeId: that.data.storeId,
        couponType: 2, //1线上券，2线下券
        token: that.data.token,
        userId: that.data.userId,
    };
    common.wxRequest("/discountCoupon/getMyCouponForStoreByType", "post", tempJson, 'application/x-www-form-urlencoded', function (res) {
        console.log(res);
        if (res.status == 200) {
            for (var i = 0; i < res.data.length; i++) {
                res.data[i].beginTime = common.dateFormat('yyyy-MM-dd', res.data[i].beginTime)
                res.data[i].endTime = common.dateFormat('yyyy-MM-dd', res.data[i].finishTime)
                res.data[i].select = false
                
                for(var j = 0;j < that.data.getSaveHasSelectList.length;j++){
                    if(res.data[i].id == that.data.getSaveHasSelectList[j]){
                        res.data[i].select = true
                    }
                }

    
            }
            var res = res.data
            // res.forEach((item, i) => {
            //     item.isSelect = false
            // })

            
            that.setData({
                cityCouponList: res,
                paymentValue: that.data.paymentValue || 0
            },()=>{
                console.log(';jjjjjj');
                that.getDiscountCoupon()
            })

        }
    });
},
  getDiscountCoupon() {
    const that = this
    const param = {
      storeId: this.data.storeId,
      userId: this.data.userId,
      token: this.data.token
    }
    common.post('/discountCoupon/showCouponOnPay', param, function (res) {
      if (res.status === 200) {
        var cityCouponList = []
        var cityCouponListss = []

        // res.data = that.data.tempVoucherList;
        // console.log('测xxxx试------',that.data.tempVoucherList);
        console.log('测试------',res.data);
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].isComposit == 1) { //isComposit ==1 不可叠加
            cityCouponList.push(res.data[i])
          } else {
            cityCouponListss.push(res.data[i])
          }
        }
        for (var i = 0; i < cityCouponList.length; i++) {
               // 歧义，为false表示未选中，true表示选中
          cityCouponList[i].select = false //三种状态 1. 遮罩层 默认不选中 同时兼顾 不选中其他的样式
          cityCouponList[i].selectTwo = false //       2. 是点击选中的状态                                   //       3. 是其他违背选中的   

            
          for(var j = 0;j < that.data.getSaveHasSelectList.length;j++){
            if(cityCouponList[i].acId == that.data.getSaveHasSelectList[j]){
                cityCouponList[i].select = true
            }
        }

        
        }

     


        for (var i = 0; i < cityCouponListss.length; i++) {
          cityCouponListss[i].select = true   // 歧义，为true表示未选中，false表示选中
          cityCouponListss[i].repeat = false
          cityCouponListss[i].selectTwo = ''

          for(var j = 0;j < that.data.getSaveHasSelectList.length;j++){
            if(cityCouponListss[i].acId == that.data.getSaveHasSelectList[j]){
                cityCouponListss[i].select = false
            }
        }

        }
        that.setData({
          // paymentValue: parseFloat(options.paymentValue)  ,  //支付金额大于等于优惠券可以使用
          cityCouponListss,

        cityCouponList: [...that.data.cityCouponList, ...cityCouponList]
        },()=>{
      

          console.log("列表--看是否选中",that.data.cityCouponList)
        })

      }
    })
  },
  useCityCoupons(e) { // 使用市券
    console.log('吸哈--');

    var totalMoeny = 0 //总优惠额度  新：选的所有类型的券的总优惠
    var coupList = [] //使用的总券   新：叠加券和不可单独使用券的券码数组
    var coupListD = [] //使用的上券  新：不可叠加券的券码数组
    var saveHasSelectList = [];
    console.log('ddd---',this.data.cityCouponList);
    for (var i = 0; i < this.data.cityCouponList.length; i++) {
      if (this.data.cityCouponList[i].select) {
        console.log("++++---++++",this.data.cityCouponList[i], "单1项")
        coupListD.push(this.data.cityCouponList[i].couponNo)// 不可叠加券的券码数组
        var discountsMoney = this.data.cityCouponList[i].discountsMoney
        totalMoeny = discountsMoney + totalMoeny // 计算不可叠加券的总优惠
        // saveHasSelectList.push(this.data.cityCouponList[i].acId?this.data.cityCouponList[i].acId:this.data.cityCouponList[i].id);
        saveHasSelectList.push(this.data.cityCouponList[i].udcId?this.data.cityCouponList[i].udcId:"");
        
      }
    }
    console.log('totalMoeny---aaa',totalMoeny);
    console.log('确定--原始所有的cityCouponListss',this.data.cityCouponListss);
    console.log('===coupListD===',coupListD);
    for (var j = 0; j < this.data.cityCouponListss.length; j++) {
     
      var selset = this.data.cityCouponListss[j].select
      if (!selset) {// 选中了
        console.log(this.data.cityCouponListss[j], "多项")
        coupList.push(this.data.cityCouponListss[j].couponNo)// 叠加券和不可单独使用券的券码数组
        saveHasSelectList.push(this.data.cityCouponListss[j].acId);
        // this.data.acIdList.push(this.data.cityCouponListss[j].id);
        if(coupList.length==1 && coupListD.length==0){// 遍历到第一个叠加券且没有非叠加券
            console.log('这里满足');
            var item = this.data.cityCouponListss.find((item)=>{
                  return item.couponNo ==coupList[0]
            })
            if(item.isComposit==3){
              common.showToast('不可单独使用')
              return
            }
            
        }
        var discountsMoneys = this.data.cityCouponListss[j].discountsMoney
        // 计算 在不可叠加券的总优惠基础上，加上叠加券和不可单独使用券的总优惠
        totalMoeny = discountsMoneys + totalMoeny 
      }
    }
    console.log('totalMoeny---bbb',totalMoeny);
    console.log('===coupList===',coupList);
    const StriCoupList = coupList.toString()
    // let cityCouponNo = e.currentTarget.dataset.item.couponNo
    // let discountMoney = e.currentTarget.dataset.item.discountsMoney

    let cityCouponNo = StriCoupList
    console.log('选中的---cityCouponNo--',cityCouponNo);

    let discountMoney = parseInt(totalMoeny*100)/100;// 选的所有类型的券的总优惠
    console.log('---discountMoney--',discountMoney);
    if (this.data.paymentValue < discountMoney) {
      common.showToast('不可超过付款额')
      return
    }
    console.log('记住已选券id',saveHasSelectList);
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; // 返会上个界面
    prevPage.setData({ // 返回携带参数给上个界面
      cityCouponNo, // 市级消费卷编码
      discountMoney, // 市级消费卷额度
      coupListD,
      saveHasSelectList,
    });
    // prevPage.refreshPage();
    wx.navigateBack({ // 返会上个界面
      delta: 1
    })
  }
})